package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    // 分页查询分类列表
    @Override
    public PageResult getCategoryList(CategoryPageQueryDTO pageParams) {
        PageHelper.startPage(pageParams.getPage(), pageParams.getPageSize());
        Page<Category> page = categoryMapper.selectCategoryList(pageParams.getName(), pageParams.getType());

        return new PageResult(page.getTotal(), page.getResult());
    }

    // 新增分类
    @Override
    public void addCategory(CategoryDTO categoryDTO) {
        Category category = new Category();

        BeanUtils.copyProperties(categoryDTO, category);
        category.setStatus(1);
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        category.setCreateUser(BaseContext.getCurrentId());
        category.setUpdateUser(BaseContext.getCurrentId());

        categoryMapper.insert(category);
    }

    // 启/禁用分类
    @Override
    public void changeStatus(Integer status, Integer id) {
        Category category = Category.builder()
                .status(status)
                .updateTime(LocalDateTime.now())
                .id(Long.valueOf(id))
                .build();

        categoryMapper.update(category);
    }

    // 修改分类
    @Override
    public void updateCategoryInfo(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        category.setUpdateUser(BaseContext.getCurrentId());
        category.setUpdateTime(LocalDateTime.now());

        categoryMapper.update(category);
    }

    @Override
    public List<Category> getCategoryByType(Integer type) {
        List<Category> categoryList = categoryMapper.selectByType(type);

        return categoryList;
    }

    @Override
    public void deleteCategoryById(Integer id) {
        categoryMapper.deleteCategoryById(id);
    }

    @Override
    public List<Category> getCategoryAll() {
        List<Category> categoryList = categoryMapper.selectAll();

        return categoryList;
    }

}
